#!/usr/bin/env python3
# ros-test-cpe.py
# CPE: Publisher to /mec/test_topic

import rclpy
from rclpy.node import Node
from std_msgs.msg import String
import time
import os

class CpeTestPublisher(Node):
    def __init__(self):
        super().__init__('cpe_test_publisher')
        self.publisher_ = self.create_publisher(String, '/mec/test_topic', 10)
        timer_period = 1.0  # seconds
        self.timer = self.create_timer(timer_period, self.timer_callback)
        self.i = 0
        self.get_logger().info('CPE Publisher started.')

    def timer_callback(self):
        msg = String()
        send_time = time.time()
        msg.data = f'Hello from CPE at {send_time:.6f}'
        self.publisher_.publish(msg)
        self.get_logger().info(f'Published: "{msg.data}"')
        self.i += 1

def main(args=None):
    rclpy.init(args=args)

    # Set ROS_DOMAIN_ID from environment (must match MEC side)
    domain_id = os.getenv('ROS_DOMAIN_ID', '42')
    os.environ['ROS_DOMAIN_ID'] = str(domain_id)

    cpe_publisher = CpeTestPublisher()

    try:
        rclpy.spin(cpe_publisher)
    except KeyboardInterrupt:
        cpe_publisher.get_logger().info('Shutting down CPE publisher...')
    finally:
        cpe_publisher.destroy_node()
        rclpy.shutdown()

if __name__ == '__main__':
    main()